package com.zengfa.task.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.zengfa.task.api.enums.RunType;
import com.zengfa.task.api.model.JobDTO;
import com.zengfa.task.api.utils.UuidUtil;
import com.zengfa.task.client.annotation.TaskCallback;
import com.zengfa.task.client.annotation.TaskNode;
import com.zengfa.task.client.annotation.TaskNodeMonitor;
import com.zengfa.task.client.annotation.TaskService;
import com.zengfa.task.client.service.JobClientService;
import com.zengfa.task.client.vo.JobContextVo;
import com.zengfa.task.client.vo.JobResult;
import com.zengfa.task.demo.service.TrainService;

@Service
@TaskService
public class TrainServiceImpl implements TrainService {

	@Autowired
	private JobClientService jobClientService;
	private static String groupName = "train";
	
	@Override
	public String startTrain() {
		String trainId = UuidUtil.getUUID32();
		JobDTO jobDTO = jobClientService.createFlowTask(groupName, trainId);
		jobClientService.runFlowTask(jobDTO);
		return null;
	}
	
	@TaskNode(group = "train", desc = "第二步", order = 2)
	public void step2(JobContextVo jobContext) {
		System.out.println("TrainService step2");
	}
	
	@TaskNode(group = "train", code = "applyResource", desc = "申请资源", order = 1)
	public void applyResource(JobContextVo jobContext) {
		System.out.println("TrainService step1");
	}
	
	@TaskNode(group = "train", desc = "第三步", order = 3, runType = RunType.ASYNC, monitorName = "trainStatusCheck")
	public void step3(JobContextVo jobContext) {
		System.out.println("TrainService step3");
	}
	
	@TaskNodeMonitor(name = "trainStatusCheck")
	public JobResult checkStatus(JobContextVo jobContext) {
		System.out.println("TrainService checkStatus");
		return JobResult.success();
	}
	
	@TaskCallback(group = "train")
	public void dealJobFinish(JobContextVo jobContext, JobResult jobResult) {
		System.out.println("TrainService dealJobFinish:" + JSONObject.toJSONString(jobResult));
	}
	
	@TaskCallback(group = "applyResource")
	public void applyResourceFinish(JobContextVo jobContext, JobResult jobResult) {
		System.out.println("TrainService applyResourceFinish:" + JSONObject.toJSONString(jobResult));
	}

	@Override
	public String applyResource() {
		String id = UuidUtil.getUUID32();
		jobClientService.runAsyncSingleTask("applyResource", id, () -> {
			System.out.println("applyResource");
		});
		return null;
	}

}
